var Env = require('./env.js')
var { getType} = require('./data_type.js')

var url = Env.domain;
// post请求的方法
var post_ = function () {
        var o = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
        o.path = (o.path.substr(0, 1) == '/' ? '' : '/') + o.path;
        return new Promise(function (resolve, reject) {
            var path = (/http/gi.test(o.path) ? o.path : url + o.path);
            o.data = o.data || {};
            o.data.sysId = getType.sysId;
            o.data.skey = lsGetStr('skey');
            return o.header || (o.header = {}), wx.request(Object.assign({
                url: path
            }, o, {
                header: Object.assign({
                    "Content-Type": "application/x-www-form-urlencoded"
                }, o.header),
                method: "POST",
                complete: function (e) {
                    var t = getCurrentPages(), n = t[t.length - 1];
                  if (200 === e.data.code || 0 === e.data.code) {
                    resolve(e.data.data || e.data.list || e.error);
                    }
                  if (200 == e.data.code || 0 === e.data.code) {
                    resolve(e.data.data || e.data.list || e.data || e.error);
                    } else {
                        reject(e.data.error);
                    }
                }
            }));
        })
    },
    // get请求的方法
    get_ = function () {
        var o = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
      o.path = (o.path.substr(0, 1) == '/' ? '' : '/') + o.path;
        var path = (/http/gi.test(o.path) ? o.path : url + o.path);
        return new Promise(function (resolve, reject) {
            wx.request(Object.assign({
                url: path + (path.indexOf('?') > -1 ? '&' : '?') 
                + 'skey=' + lsGetStr('skey')
                + '&sysId=' + getType.sysId
            }, o, {
                complete: function (e) {
                  if (200 == e.data.code || 0 === e.data.code) {
                    resolve(e.data.list || e.data.data || e.data || e.error);
                    } else {
                        if (e.data.code == 403) {
                            if (e.data.error.indexOf('skey') > -1
                                || e.data.error.indexOf('未登录') > -1) {
                                // return wx.reLaunch({
                                //     url: '/pages/home2/index?msg=请注册后继续操作～',
                                // })
                            }
                            reject(e.data.error);

                        } else {
                            reject(e.data.error);

                        }
                    }
                },
                method: "GET"
            }))
        });
    };


function lsSetObj(key, obj) {
    wx.setStorageSync(key, JSON.stringify(obj || {}))
}
function lsSetStr(key, str) {
    wx.setStorageSync(key, str)
}
function lsGetObj(key) {
    let strObj = wx.getStorageSync(key);
    if (!strObj) {
        if (key == 'loginedUser') {
          let page = getCurrentPages();
          if (
            page 
            && page.length 
            && page.route 
            && page.route.indexOf('/pages/home2/index')==-1
          ){ //非首页进行切换至首页
            wx.navigateTo({
              url: '/pages/home2/index'
            });
          }
          console.log('111')
          return {};
        }
        return {}
    }
    return JSON.parse(wx.getStorageSync(key));
}
function lsGetStr(key) {
    return (wx.getStorageSync(key));
}

/**
 * GET请求
 * @returns {Promise}
 */
exports.get = get_;
/**
 * POST请求
 * @returns {Promise}
 */
exports.post = post_;


/**
 * 登录接口
 * @param e
 * @returns {*}
 */
exports.login = function (e) {
    return new Promise(function (resolve, reject) {
        //console.log(e.detail.encryptedData);
        // debugger;
        wx.login({
            success: function (t) {
                return get_({
                    path: "wx/xcx-login",
                    data: {
                        partnerId: lsGetStr('partnerId'),//合伙人分享ID
                        code: t.code,
                        encrypteData: e.detail.encryptedData,
                        iv: e.detail.iv,
                        rawData: e.detail.rawData,
                        signature: e.detail.signature
                    }
                })
                    .then(function (res1) {
                        // console.log(res1);
                        lsSetStr('loginedUser', (res1.userInfo));
                        lsSetStr('skey', res1.skey || '');
                        resolve(res1);
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            fail: function (error) {
                console.log(error);
                reject(error || '没有登录成功～，请重试！');
            }
        })
    })
};

exports.checkCoupon = function (flag) {

  var e = getCurrentPages(), t = e[e.length - 1];

  t.setData({
    couponsBg: (!wx.getStorageSync("couponsBg")) ? true : false
  });
};


exports.fnRequest = function (opt, ctx) {
    wx.request(Object.assign({}, {
        url: opt.url || '',
        data: opt.data,
        method: opt.method || 'GET',
        header: opt.header || {},
        success: function (res) {
            if (res.data.code == 401 || (res.data.code == 403 && res.data.error.indexOf('未登录') > -1)) {
                ctx && ctx.setData({
                    loginBgFlag: !0
                })
            }
            opt.success && opt.success(res);

        },
        fail: function (error) {
            opt.fail && opt.fail(res);
        }
    }, opt.dataType ? {dataType: opt.dataType} : {}));
};
exports.fnUpload = function (opt) {
    return new Promise(function (resolve, reject) {
        wx.uploadFile({
            url: url + 'uploadOss',
            filePath: opt.filePath || '',
            name: 'file',
            success: function (res) {
                console.log(res);
                resolve(res.data);
            },
            fail: function (error) {
                reject(error)
            }
        })
    })

};
/**
 * 选择文件
 * @param opt
 * @returns {Promise}
 */
exports.fnChoose = function (opt={}) {
    return new Promise(function (resolve, reject) {
        wx.chooseImage({
            count: opt.count || 1, // 最多可以选择的图片张数，默认9
            sizeType: ['compressed'], // original 原图，compressed 压缩图，默认二者都有
            sourceType: opt.sourceType || ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
            success: function (res) {
                console.log(res.tempFilePaths + "修改页面")
                resolve(res.tempFilePaths);
            },
            fail: function (err) {
                reject(err);
            },
        })
    })

};
exports.lsGetObj = lsGetObj;
exports.lsGetStr = lsGetStr;
exports.lsSetStr = lsSetStr;
exports.lsSetObj = lsSetObj;
